package com.xucranger.ojapi.utils;

import com.xucranger.ojapi.enity.DTO.common.PageResultDTO;
import com.xucranger.ojapi.enity.VO.CommonContestVO;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class SmartBeanUtil {

    /**
     * 复制bean的属性
     *
     * @param source 源 要复制的对象
     * @param target 目标 复制到此对象
     */
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    /**
     * 复制对象
     *
     * @param source 源 要复制的对象
     * @param target 目标 复制到此对象
     * @param <T>
     * @return
     */
    public static <T> T copy(Object source, Class<T> target) {
        if(source == null || target == null){
            return null;
        }
        try {
            T newInstance = target.newInstance();
            BeanUtils.copyProperties(source, newInstance);
            return newInstance;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制list
     *
     * @param source
     * @param target
     * @param <T>
     * @param <K>
     * @return
     */
    public static <T, K> List<K> copyList(List<T> source, Class<K> target) {

        if (null == source || source.isEmpty()) {
            return Collections.emptyList();
        }
        return source.stream().map(e -> copy(e, target)).collect(Collectors.toList());
    }

    public static <T>  PageResultDTO<CommonContestVO> conver2commoncontest(PageResultDTO<T> resultDTO){
        List<CommonContestVO> entities = new ArrayList<>();
        PageResultDTO<CommonContestVO> listDto = new PageResultDTO<>();
        entities = SmartBeanUtil.copyList(resultDTO.getList(),CommonContestVO.class);
        listDto.setList(entities);
        listDto.setPageNum(resultDTO.getPageNum());
        listDto.setPageSize(resultDTO.getPageSize());
        listDto.setTotal(resultDTO.getTotal());
        listDto.setPages(resultDTO.getPages());
        return listDto;
    }


}
